<template>
  <div class="category">
    <h1>{{ id ? "编辑" : "新增" }}广告</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="广告名称:">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="名称:">
        <el-button size="small" @click="form.items.push({})"><i class="el-icon-plus"></i> 添加广告</el-button>
        <el-row type="flex" style="flex-wrap:wrap">
          <el-col :md="6" v-for="(item, index) in form.items" :key="index">
            <el-form-item label="跳转地址：">
              <el-input v-model="item.url"></el-input>
            </el-form-item>
            <el-form-item label="图片:">
              <el-upload :class="['avatar-uploader',item.showErr?'errline':'']" style="margin-top:1rem" :action="uploadUrl" :headers="getAuthHeads" :show-file-list="false" :on-success="afterupload">
                <img v-if="item.url" :src="item.url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <!-- <p v-if="item.showErr" style="color:red"> 请上传图片</p> -->
              </el-upload>
            </el-form-item>
            <el-form-item label="操作：">
              <el-button type="danger" size="small" @click="form.items.splice(index,1)">删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import http from "../axios/index.js";
export default {
  props: {
    id: String,
  },
  data() {
    return {
      form: { items: [] },
      parents: [],
    };
  },
  created() {
    this.id && this.fetch();
    this.fetchParent();
  },
  methods: {
    // 图片上传之后
    afterupload(res) {
      this.$set(this.form, "avatar", res.url);
      // this.form.icon = res.url;
    },
    // 获取
    async fetch() {
      const res = await this.$http.get(`/rest/ads/${this.id}`);
      this.form = res.data;
    },
    async fetchParent() {
      const res = await this.$http.get(`/rest/ads`);
      this.parents = res.data;
    },
    async save() {
      let res;
      // 图片上传校验
      // this.form.items.forEach((item) => {
      //   if (!item.url) this.$set(item, "showErr", true);
      // });
      // return;
      if (this.id) {
        res = await this.$http.put(`/rest/ads/${this.id}`, this.form);
      } else {
        res = await this.$http.post("/rest/ads", this.form);
      }
      const { data } = res;
      if (data.code == 200) {
        this.$message.success(data.msg);
        this.$router.push("/ads/list");
      }
    },
  },
};
</script>

<style>
.errline {
  border: 1px solid red;
}
</style>
